package com.anti.modular.sys.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.anti.jdbc.DBUtils;
import com.anti.modular.sys.role.service.SysRoleService;
import com.anti.modular.sys.user.dao.SysUserDao;
import com.anti.modular.sys.user.entity.SysUser;
import com.anti.modular.sys.user.entity.SysUserRole;
import com.anti.modular.sys.user.param.SysUserParam;
import com.anti.modular.sys.user.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2021-3-10
 */
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {
    @Resource
    DBUtils dbUtils;
    @Resource
    SysRoleService sysRoleService;

    @Override
    public List<Long> getUserRoleIdList(Long userId) {
        String sql="select DISTINCT id from sys_role where id in (select role_id from sys_user_role where user_id=?)";
        return dbUtils.query(sql,Long.class,userId);
    }

    @Override
    public void deleteUserRoleListByUserId(Long userId) {
        String deleteSql="delete from  sys_user_role where user_id=?";
        dbUtils.execSql(deleteSql,userId);
    }

    @Override
    public void saveGrantRole(SysUserParam sysUserParam) {
        Long userId = sysUserParam.getId();
        //删除所拥有角色
        String removeSql="delete from sys_user_role where user_id=?";
        dbUtils.execSql(removeSql,userId);
        //授权角色
        String sql="insert into sys_user_role (user_id,role_id) values (?,?)";
        sysUserParam.getGrantRoleIdList().forEach(roleId -> {
            dbUtils.execSql(sql,userId,roleId);
        });
    }

    @Override
    public List<Long> getUserRoleDataScopeIdList(Long userId, Long orgId) {
        // 获取用户所有角色
        String sql="select role_id from sys_user_role where user_id=?";
        List<Long> roleIdList = dbUtils.query(sql, Long.class, userId);
        // 获取这些角色对应的数据范围
        if (ObjectUtil.isNotEmpty(roleIdList)) {
            return sysRoleService.getUserDataScopeIdList(roleIdList, orgId);
        }
        return CollectionUtil.newArrayList();
    }
}
